package cn.qyd.kaoshi;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 邱运铎
 * leecode中一个人使用的空间占用最小的方法，试一下
 * @date 2024-03-24 0:58
 */
public class RottenOrangeUpgrade01 {
    public static void main(String[] args) {
        RottenOrangeUpgrade01 or = new RottenOrangeUpgrade01();
        int[][] grid = new int[][]{{2,1,1},{1,1,0},{0,1,1}};
//        int[][] grid = new int[][]{{2,1,1},{0,1,1},{1,0,1}};
        int result = or.orangesRotting(grid);
        System.out.println(result);
    }
    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        Queue<int[]> queue = new LinkedList<>();
        int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    count++;
                } else if (grid[i][j] == 2) {
                    queue.add(new int[]{i,j,0});
                }
            }
        }
        int total = 0;
        while (!queue.isEmpty()) {
            int[] cur = queue.remove();
            int x = cur[0], y = cur[1],min = cur[2];
            total = Math.max(total,min);

            for (int i = 0; i < dirs.length; i++) {
                int x1 = x + dirs[i][0];
                int y1 = y + dirs[i][1];

                if(x1 >= 0 && x1 < m && y1 >= 0 && y1 < n && grid[x1][y1] == 1) {
                    grid[x1][y1] = 2;
                    count--;
                    queue.add(new int[]{x1,y1,min+1});
                }
            }
        }

        return count > 0 ? -1 : total;
    }
}
